package com.sqoq.downloader3.videolist_ddg

import android.content.Context
import android.content.Intent
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.viewpager.widget.ViewPager
import com.gyf.immersionbar.ImmersionBar
import com.sqoq.downloader3.R
import com.sqoq.downloader3.adapter_ddg.Tiktok2Adapter
import com.sqoq.downloader3.base_ddg.BaseActivity_ddg
import com.sqoq.downloader3.bean_ddg.VideoListBean_ddg
import com.sqoq.downloader3.databinding.ActivityVideoListDdgBinding
import com.sqoq.downloader3.videolist_ddg.cache.PreloadManager
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.util.L

class VideoListActivity_ddg : BaseActivity_ddg<ActivityVideoListDdgBinding>() {
    companion object {
        @JvmStatic
        fun start(context: Context, data: VideoListBean_ddg) {
            val starter = Intent(context, VideoListActivity_ddg::class.java)
                .putExtra("data", data).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(starter)
        }
    }

    private var index: Int = 0

    /**
     * 当前播放位置
     */
    private var mCurPos = 0
    private val mVideoList: MutableList<VideoListBean_ddg> = ArrayList()
    private var mTiktok2Adapter: Tiktok2Adapter? = null
    private lateinit var mViewPager: VerticalViewPager
    private var mPreloadManager: PreloadManager? = null
    private var mController: TikTokController? = null

    protected var mVideoView: VideoView? = null
    override val layout: Int
        get() = R.layout.activity_video_list_ddg

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .navigationBarColor(R.color.white)
            .statusBarDarkFont(false)
            .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED)
            .keyboardEnable(true)
            .flymeOSStatusBarFontColor(android.R.color.white) //修改 flyme OS 状态栏字体颜色
            .init()
    }

    override fun initView() {
        initViewPager()
        initVideoView()
//        mPreloadManager = PreloadManager.getInstance(this)
        var data:VideoListBean_ddg = intent.getSerializableExtra("data") as VideoListBean_ddg
        mVideoList.add(data)
        mTiktok2Adapter!!.notifyDataSetChanged()
        startPlay(index)

        mViewPager!!.currentItem = index
        mViewPager!!.post { startPlay(index) }
    }

    private fun initVideoView() {
        mVideoView = VideoView(this)
        mVideoView!!.setLooping(true)

        //以下只能二选一，看你的需求
        mVideoView!!.setRenderViewFactory(TikTokRenderViewFactory.create())
//        mVideoView!!.setRenderViewFactory(SurfaceRenderViewFactory.create())

        mController = TikTokController(this)

//        val completeView = CompleteView(baseContext)
//        val errorView = ErrorView(baseContext)
//        val prepareView = PrepareView(baseContext)
//        prepareView.setClickStart()
//        mController?.addControlComponent(completeView, errorView, prepareView)
//        mController?. addControlComponent(VodControlView(baseContext))
//
        mVideoView!!.setVideoController(mController)
    }

    private fun initViewPager() {
        mViewPager = binding.vie
        mViewPager.setOffscreenPageLimit(4)
        mTiktok2Adapter = Tiktok2Adapter(mVideoList)
        mViewPager.setAdapter(mTiktok2Adapter)
        mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER)
        mViewPager.setOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            private var mCurItem = 0

            /**
             * VerticalViewPager是否反向滑动
             */
            private var mIsReverseScroll = false
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                if (position == mCurItem) {
                    return
                }
                mIsReverseScroll = position < mCurItem
            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (position == mCurPos) return
                startPlay(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                if (state == VerticalViewPager.SCROLL_STATE_DRAGGING) {
                    mCurItem = mViewPager.getCurrentItem()
                }
                if (state == VerticalViewPager.SCROLL_STATE_IDLE) {
//                    mPreloadManager!!.resumePreload(mCurPos, mIsReverseScroll)
                } else {
//                    mPreloadManager!!.pausePreload(mCurPos, mIsReverseScroll)
                }
            }
        })
    }

    private fun startPlay(position: Int) {
        val count = mViewPager!!.childCount
        for (i in 0 until count) {
            val itemView = mViewPager!!.getChildAt(i)
            val viewHolder = itemView.tag as Tiktok2Adapter.ViewHolder
            if (viewHolder.mPosition == position) {
                mVideoView!!.release()
                removeViewFormParent(mVideoView)
                val tiktokBean = mVideoList[position]
//                val playUrl = mPreloadManager!!.getPlayUrl(tiktokBean.url_mm)
                val playUrl = tiktokBean.filePath_ddg
                L.i("startPlay: position: $position  url: $playUrl")

                mVideoView!!.setUrl(playUrl)
                //请点进去看isDissociate的解释
                mController!!.addControlComponent(viewHolder.mTikTokView, true)

                viewHolder.mPlayerContainer.addView(mVideoView, 0)
                mVideoView!!.start()
                mCurPos = position
                break
            }
        }
    }

    fun removeViewFormParent(v: View?) {
        if (v == null) return
        val parent = v.parent
        if (parent is FrameLayout) {
            parent.removeView(v)
        }
    }

    override fun onResume() {
        super.onResume()
        if (mVideoView != null) {
            mVideoView!!.resume()
        }
    }


    override fun onPause() {
        super.onPause()
        if (mVideoView != null) {
            mVideoView!!.pause()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mVideoView != null) {
            mVideoView!!.release()
        }

//        mPreloadManager!!.removeAllPreloadTask()
        //清除缓存，实际使用可以不需要清除，这里为了方便测试
//        ProxyVideoCacheManager.clearAllCache(this)
    }
}